/**
 * 接口请求token校验
 */
import {
  CanActivate,
  ExecutionContext,
  HttpException,
  Injectable,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';
interface Request {
  headers: any;
  user: {
    id: number;
    username: string;
    role: string
  };
}
@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly jwtSevice: JwtService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    const token = request.headers['token'];
    try {
      const res = this.jwtSevice.verify(token, { secret: 'kylin' });
      request.user = res;
    } catch {
      throw new HttpException('登录失效请重新登陆', 400);
    }
    return true;
  }
}
